from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.views import APIView
from .serializers import OrderSerializer
from rest_framework.response import Response
from rest_framework import status
from .models import Order
from django.utils import timezone
from datetime import timedelta


# Create your views here.
class OrderViewSet(viewsets.ModelViewSet):
    serializer_class = OrderSerializer
    queryset = Order.objects.all()

    def get_queryset(self):
        queryset = super().get_queryset()
        name = self.request.query_params.get('name', None)
        if name is not None:
            queryset = queryset.filter(name=name)
        return queryset

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # address = serializer.validated_data.pop('address')
        address = request.data.get('address')
        province_id, city_id, district_id = address

        serializer.validated_data['province_id'] = province_id
        serializer.validated_data['city_id'] = city_id
        serializer.validated_data['district_id'] = district_id

        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response({'success': True}, status=status.HTTP_201_CREATED)


class OrdersCountView(APIView):
    """订单数量"""

    def get(self, request):
        """获取订单总数量、最近三天订单数量"""
        count = Order.objects.all().count()
        three_days_ago = timezone.now() - timedelta(days=3)
        orders = Order.objects.filter(created_at=three_days_ago)
        data = {
            'count': count
        }
        return Response(data)


class RecentOrdersView(APIView):
    """订单数量"""

    def get(self, request, days):
        """最近几天订单数量"""
        days_ago = timezone.now() - timedelta(days=days)
        print(days_ago)
        orders = Order.objects.filter(created_at__gte=days_ago)
        serializer = OrderSerializer(orders, many=True)
        count = orders.count()
        data = {
            'count': count,
            'data': serializer.data
        }
        return Response(data)
